package com.ias.agdis_r.activity.task;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.ias.agdis_r.R;
import com.ias.agdis_r.activity.BaseActivity;
import com.ias.agdis_r.adapter.QJMonitorAdapter;
import com.ias.agdis_r.bean.task.FLG10TaskBean;
import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.module.MessageModel;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.response.BaseResponse;
import com.ias.agdis_r.view.control.EditorTextClear;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 清洁监控界面
 * Created by guoxr on 2015/12/2.
 */
public class QJMonitorActivity extends BaseActivity {
    private ActionBar actionBar;
    private ListView listView;
    private boolean isFilter = true;
    private QJMonitorAdapter adapter;
    private TextView number;
    private List<FLG10TaskBean> _mylist = new ArrayList<FLG10TaskBean>();
    private Button btn_top, btn_bottom;
    private String[] spItem = null;
    private Spinner mSpinner; // 过滤条件选择
    private Spinner tstSpinner; // 状态类的子过滤条件选择
    private EditorTextClear et_text;
    private ArrayAdapter<String> spAdapter;
    private ArrayAdapter<String> tstAdapter;
    private ArrayList<String> tstList = new ArrayList<String>();
    private int pos = 0; // 记录当前mSpinner选中项
    private String digits = "/\\:*?<>|\"\n\t";
    private AlertDialog dialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qj_monitor);
        spItem = new String[]{getString(R.string.flno), getString(R.string.regnumber), getString(R.string.placecode), getString(R.string.AT_4)};
        actionBar = getActionBar();
        initactionBar();
        setListAdapter();
    }

    @Override
    protected void onResume() {
        super.onResume();
        chooseDate();
        int selectPos = JavaBeanManager.getInstance().getSelectPos();
        if (selectPos > 0 && selectPos < _mylist.size()) {
            listView.setSelection(selectPos);
        }
    }

    private void chooseDate() {
        String[] stateArray = JavaBeanManager.getInstance().getQJMonitorState()
                .split(",");
        if (2 == stateArray.length) {
            setDate(stateArray[0], stateArray[1]);
        } else if (1 == stateArray.length) {
            setDate(stateArray[0], "");
        } else {
            onCreateArrayList();
        }
        bindData();
    }

    private void setDate(String method, final String value) {
        getFilterList(method, value);
        setSpinner(method);
        DataBaseManager.getInstance().getUIHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (et_text.getVisibility() == View.VISIBLE) {
                    et_text.setText(value);
                } else {
                    setTstList(value);
                }
            }
        }, 500);
    }

    private void setSpinner(String method) {
        String name = null;
        if (method.equals("getFln")) {
            name = getString(R.string.flno);
        } else if (method.equals("getReg")) {
            name = getString(R.string.regnumber);
        } else if (method.equals("getPsn")) {
            name = getString(R.string.placecode);
        } else if (method.equals("getTst")) {
            name = getString(R.string.AT_4);
        }
        int i = Arrays.asList(spItem).indexOf(name);
        if (i >= 0 && i < spItem.length) {
            mSpinner.setSelection(i);
        }
    }

    private void setListAdapter() {
        number = (TextView) findViewById(R.id.tv_number);
        listView = (ListView) findViewById(R.id.ListView);
        adapter = new QJMonitorAdapter(QJMonitorActivity.this, _mylist);
        listView.setAdapter(adapter);
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == 0) {
                    if (listView.getFirstVisiblePosition() == 0) {
                        btn_top.setVisibility(View.GONE);
                        btn_bottom.setVisibility(View.VISIBLE);
                    } else if (listView.getFirstVisiblePosition() >= adapter.getCount() - 4) {
                        btn_top.setVisibility(View.VISIBLE);
                        btn_bottom.setVisibility(View.GONE);
                    } else {
                        btn_top.setVisibility(View.VISIBLE);
                        btn_bottom.setVisibility(View.VISIBLE);
                    }
                } else {
                    btn_top.setVisibility(View.GONE);
                    btn_bottom.setVisibility(View.GONE);
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
        btn_top = (Button) findViewById(R.id.btn_top);
        if (JavaBeanManager.getInstance().getSelectPos() == 0) {
            btn_top.setVisibility(View.GONE);
        }
        btn_top.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listView.setSelection(0);
                btn_top.setVisibility(View.GONE);
                btn_bottom.setVisibility(View.VISIBLE);
            }
        });
        btn_bottom = (Button) findViewById(R.id.btn_bottom);
        btn_bottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listView.setSelection(listView.getBottom());
                btn_top.setVisibility(View.VISIBLE);
                btn_bottom.setVisibility(View.GONE);
            }
        });
    }

    private void initactionBar() {
        actionBar.setCustomView(LayoutInflater.from(QJMonitorActivity.this).inflate(R.layout.actionbar_qj_monitor, null));
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        actionBar.setDisplayShowCustomEnabled(true);
        ImageView back = (ImageView) findViewById(R.id.actionbar_qjmonitor_back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                finish();
            }
        });
        ImageView tem = (ImageView) findViewById(R.id.actionbar_qjmonitor_menu);
        tem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null && dialog.isShowing())
                    dialog.dismiss();
                showMenuDialog();
            }
        });
        et_text = (EditorTextClear) findViewById(R.id.actionbar_qjmonitor_filte);
        et_text.addTextChangedListener(new TextWatcher() {
            String tmp = "";
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                et_text.setSelection(s.length());
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (isFilter) {
                            isFilter = false;
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            DataBaseManager.getInstance().getUIHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    filteDate(pos);
                                    isFilter = true;
                                }
                            });
                        }
                    }
                }).start();
                String str = s.toString();
                if (str.equals(tmp)) {
                    return;
                }
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < str.length(); i++) {
                    if (digits.indexOf(str.charAt(i)) < 0) {
                        sb.append(str.charAt(i));
                    }
                }
                tmp = sb.toString();
                et_text.setText(tmp);
            }
        });

        mSpinner = (Spinner) findViewById(R.id.sp_item);
        spAdapter = new ArrayAdapter<String>(QJMonitorActivity.this, android.R.layout.simple_spinner_item, spItem);
        spAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mSpinner.setAdapter(spAdapter);
        mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                                       int arg2, long arg3) {
                if (arg2 == 3) {
                    et_text.setVisibility(View.GONE);
                    tstSpinner.setVisibility(View.VISIBLE);
                    getFilterList("getTst", "");
                    setTstList("");
                    bindData();
                    pos = arg2;
                } else {
                    tstSpinner.setVisibility(View.GONE);
                    et_text.setVisibility(View.VISIBLE);
                    et_text.setText("");
                    filteDate(arg2);
                    pos = arg2;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
            }
        });
        tstSpinner = (Spinner) findViewById(R.id.sp_item2);
        tstAdapter = new ArrayAdapter<String>(QJMonitorActivity.this,
                android.R.layout.simple_spinner_item, tstList);
        tstAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        tstSpinner.setAdapter(tstAdapter);
        tstSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                                       int arg2, long arg3) {
                String tst = tstList.get(arg2);
                if (tst.equals(getString(R.string.all))) {
                    getFilterList("getTst", "");
                } else {
                    getFilterList("getTst", tst);
                }
                bindData();
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
            }
        });
    }

    private void showMenuDialog(){
        final String[] strings = new String[]{getString(R.string.barchart),getString(R.string.QJ_expandable)};
        AlertDialog.Builder bulider = new AlertDialog.Builder(QJMonitorActivity.this);
        bulider.setTitle(getString(R.string.chooseOperat));
        bulider.setIcon(android.R.drawable.ic_dialog_info);
        bulider.setSingleChoiceItems(strings, 0, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (getString(R.string.barchart).equals(strings[which])){
                            startActivity(new Intent(QJMonitorActivity.this, TaskBarChartActivity.class));
                        }else if (getString(R.string.QJ_expandable).equals(strings[which])){
                            startActivity(new Intent(QJMonitorActivity.this, QJMonitorExpandableActivity.class));
                        }
                    }
                });
        bulider.setNegativeButton(getString(R.string.cancel), null);
        dialog = bulider.create();
        dialog.show();
    }



    /**
     * 创建数组获取数据
     */
    private void onCreateArrayList() {
        ArrayList<FLG10TaskBean> list = JavaBeanManager.getInstance()
                .getFLG10Taskinfo().getList();
        if (null != list) {
            _mylist.clear();
            _mylist.addAll(JavaBeanManager.getInstance().deleteEndTask(list));
        }
    }

    private void setTstList(String value) {
        tstList.clear();
        tstList.add(getString(R.string.all));
        // 找出监控任务所有未结束的节点，保存至tstList
        List<FLG10TaskBean> list = JavaBeanManager.getInstance()
                .deleteEndTask(JavaBeanManager.getInstance().getFLG10Taskinfo().getList());
        if (list != null) {
            for (FLG10TaskBean taskBean : list) {
                if (tstList.indexOf(taskBean.getTst()) == -1) {
                    tstList.add(taskBean.getTst());
                }
            }
            tstAdapter.notifyDataSetChanged();
            int i = tstList.indexOf(value);
            if (value.equals("")) {
                tstSpinner.setSelection(0);
            } else if (i >= 0 && i < tstList.size()) {
                tstSpinner.setSelection(i);
            }
        }
    }

    private void filteDate(int position) {
        String input = et_text.getText().toString();
        if (0 == position) {
            getFilterList("getFln", input);
        } else if (1 == position) {
            getFilterList("getReg", input);
        } else if (2 == position) {
            getFilterList("getPsn", input);
        }
        bindData();
    }

    /**
     * 获取过滤后的数据
     */
    private void getFilterList(String method, String value) {
        JavaBeanManager.getInstance().saveQJMonitorState(method + "," + value);
        ArrayList<FLG10TaskBean> list = new ArrayList<FLG10TaskBean>();
        try {
            list = JavaBeanManager.getInstance().getFiltedList(method, value);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (null != list) {
            _mylist.clear();
            _mylist.addAll(JavaBeanManager.getInstance().deleteEndTask(list));
        }
    }

    private void bindData() {
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
        if (number != null && btn_top != null && btn_bottom != null) {
            number.setText(getString(R.string.QJMA_1) + _mylist.size() + getString(R.string.QJMA_2));
            if (_mylist.size() < 4) {
                btn_top.setVisibility(View.GONE);
                btn_bottom.setVisibility(View.GONE);
            }
        }
    }

    @Override
    protected void operateResponseSucess(String serviceId, BaseResponse response) {

    }

    @Override
    protected void updateUI(String tag) {
        if (tag.equals(MessageModel.ITTL)) {
            chooseDate();
        }
    }

    @Override
    protected void onPause() {
        JavaBeanManager.getInstance().setSelectPos(listView.getFirstVisiblePosition());
        super.onPause();
    }

    @Override
    protected void onMenuKeyDown() {
        //如果当前显示的fragment是任务界面
        if (dialog == null || !dialog.isShowing()){
            showMenuDialog();
        }
    }
}
